package com.summer.order.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.summer.config.model.Config;
import com.summer.config.service.ConfigService;
import com.summer.core.annotations.ScopeType;
import com.summer.core.controller.EntityHome;
import com.summer.core.service.BaseService;
import com.summer.core.util.DateUtil;
import com.summer.core.util.FacesUtil;
import com.summer.core.util.LocalConstants;
import com.summer.dingding.model.DingDingMessageTemplate;
import com.summer.dingding.model.DingDingUser;
import com.summer.dingding.service.DingDingMessageService;
import com.summer.dingding.service.DingDingService;
import com.summer.order.model.Cookbook;
import com.summer.order.model.DayFood;
import com.summer.order.model.ReportOrder;
import com.summer.order.model.UserOrder;
import com.summer.order.service.UserOrderService;
import com.summer.order.util.OrderConstants;

@Component
@Scope(ScopeType.VIEW)
public class CookbookHome extends EntityHome<Cookbook> {

	@Resource
	BaseService<Cookbook> baseService;
	
	@Resource
	DingDingService dingDingService;
	
	@Resource
	DingDingMessageService dingDingMessageService;
	
	@Resource
	ConfigService configService;
	
	@Resource
	UserOrderService userOrderService;
	
	@Resource
	HibernateTemplate ht;
	// private Integer count;

	DayFood[] dayFoods = new DayFood[20];

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String save() {

		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		Cookbook cookbook = getInstance();

		String startDateStr = df.format(cookbook.getStartDate());
		String endDateStr = df.format(cookbook.getEndDate());
		if (cookbook.getId().equals("") || cookbook.getId() == null) {
			cookbook.setId(startDateStr + endDateStr);
		}
		cookbook.setDateBetween(startDateStr + "-" + endDateStr);

		delete(cookbook.getId());
		List<DayFood> dayFoodList = getDayFoodList();
		List<DayFood> dayFoodListNew = new ArrayList<DayFood>();

		for (int i = 0; i < dayFoodList.size(); i++) {
			DayFood dayFood = dayFoodList.get(i);

			if (dayFood.getDate() == null
					&& (dayFood.getFood1() != null || dayFood.getFood2() != null)) {
				FacesUtil.addErrorMessage("日期不能为空");
				return null;
			}
			if (dayFood.getDate() != null
					&& (dayFood.getFood1() == null && dayFood.getFood2() == null)) {
				FacesUtil.addErrorMessage("请至少选择一个菜");
				return null;
			}
			if (dayFood.getDate() == null && dayFood.getFood1() == null
					&& dayFood.getFood2() == null) {
				continue;
			}

			String dateStr = df.format(dayFood.getDate());
			if (Integer.parseInt(startDateStr) > Integer.parseInt(endDateStr)) {
				FacesUtil.addErrorMessage("起始时间大于截止时间了，这样不行的！");
				return null;
			}
			if (Integer.parseInt(dateStr) > Integer.parseInt(endDateStr)
					|| Integer.parseInt(dateStr) < Integer
							.parseInt(startDateStr)) {
				FacesUtil.addErrorMessage("日期选错了，得在起止时间之内啊！");
				return null;
			}
			for (int j = 0; j < dayFoodList.size(); j++) {
				if (j == i) {
					continue;
				}
				if (dayFoodList.get(j).getDate() == null) {
					continue;
				}
				if (dateStr.equals(df.format(dayFoodList.get(j).getDate()))) {
					FacesUtil.addErrorMessage("日期选重复了");
					return null;
				}
			}
			dayFood.setId(dateStr);
			dayFood.setCookbook(cookbook);
			dayFood.setLunch(true);
			dayFood.setBreakfast(false);
			dayFoodListNew.add(dayFood);
		}

//		System.out.println(dayFoodListNew.size());

		if(dayFoodListNew == null || dayFoodListNew.size() == 0) {
			FacesUtil.addErrorMessage("你这一天都没选啊，根本不能让你存！");
			return null;
		}
		cookbook.setDayFoods(new HashSet<DayFood>(dayFoodListNew));
		cookbook.setStatus(OrderConstants.CookbookStatus.SEND_ORDER_NOTICE);

		
		baseService.save(cookbook);
		FacesUtil.addInfoMessage("添加成功了，yeah！");
		return FacesUtil.redirect("/admin/order/cookbookList");
	}
	/**
	 * 发送订餐通知
	 * @param cookbookId
	 */
	public String sendOrderNotice(String cookbookId) {
		Cookbook cb = ht.get(Cookbook.class, cookbookId);
		String dateBetween = cb.getDateBetween();
		String end_time = "14:30";
		String breakfast_str = "每周二早餐纯肉馄饨，每周四早餐芹菜肉、酸菜肉馅饼";
		Config order_end_time = ht.get(Config.class, "order_end_time");
		if (order_end_time != null && !StringUtils.isEmpty(order_end_time.getValue())) {
			end_time = order_end_time.getValue();
		}
		Config breakfast = ht.get(Config.class, "breakfast_str");
		if (breakfast != null && !StringUtils.isEmpty(breakfast.getValue())) {
			breakfast_str = breakfast.getValue();
		}
		DingDingMessageTemplate message = null;
		int pre = new Double(Math.random() * 993).intValue() + 1;
		String image = LocalConstants.Config.LOCAL_URL + "/include/images/emoticon/" + pre + ".jpg";
		String content = "订饭了订饭了，订餐周期：" + dateBetween + "，截止至" + end_time + "，" + breakfast_str + "。";
		message = dingDingMessageService.buildSendMessage("http://mia.summor.cn", "订餐啦！订餐啦！", content , "老夏", image, null);
		List<DingDingUser> duserList = ht.find("from DingDingUser d where d.bindStatus = '1' and d.user.id is not null order by id desc");
		int size = duserList.size();
		for (int i = 0; i <=  size / 20; i++) {
			int x = (i+1) * 20 > size ? size :(i+1) * 20;
			List<DingDingUser> newList = duserList.subList(i*20, x);
			int sizeNew = newList.size();
			StringBuffer sb = new StringBuffer();
			for (int j = 0; j < sizeNew; j++) {
				sb.append(newList.get(j).getUserid());
				if(j != sizeNew - 1) {
					sb.append(",");
				}
			}
			try {
				JSONObject json = dingDingService.sendDDMessage(sb.toString(), message);
				System.out.println(sb);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		cb.setStatus(OrderConstants.CookbookStatus.ENABLE);
		baseService.merge(cb);
		return getUpdateView();
	}
	
	
	public String sendOrderCompleteNotice(String cookbookId) throws ParseException {
		Cookbook cb = ht.get(Cookbook.class, cookbookId);
		String end_time = "14:30";
		Config order_end_time = ht.get(Config.class, "order_end_time");
		if (order_end_time != null && !StringUtils.isEmpty(order_end_time.getValue())) {
			end_time = order_end_time.getValue();
		}
		
		end_time = new SimpleDateFormat("yyyyMMdd").format(new Date()) + " " + end_time +":00";
		Date endDate = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(end_time);
		Long minutes = Math.abs(DateUtil.getIntervalTimes(endDate)/1000/60);
		
		List<UserOrder> userOrderList = ht.find("from UserOrder uo where uo.dateBetween = ? or uo.cookbook_id = ?",cb.getDateBetween() , cb.getId());
		ReportOrder ro = userOrderService.getReportOrder(userOrderList);
		List<Map<String, String>> form = new ArrayList<Map<String,String>>();
		Map<String, String> form1 = new HashMap<String, String>();
		form1.put("key", "订餐人数：");
		form1.put("value", ""+ro.getCountMember());
		Map<String, String> form2 = new HashMap<String, String>();
		form2.put("key", "早餐总数：");
		form2.put("value", ""+ro.getCountBreakfast());
		Map<String, String> form3 = new HashMap<String, String>();
		form3.put("key", "午餐总数：");
		form3.put("value", ""+ro.getCountLunch());
		form.add(form1);
		form.add(form2);
		form.add(form3);
		
		DingDingMessageTemplate message = null;
		int pre = new Double(Math.random() * 993).intValue() + 1;
		String image = LocalConstants.Config.LOCAL_URL + "/include/images/emoticon/" + pre + ".jpg";
		String content = "本期菜单还有" + minutes.intValue() + "分钟截止了嗷~~没订的抓紧哈！订好的准备好现金！支持微信支付宝。" ;
		message = dingDingMessageService.buildSendMessage("http://mia.summor.cn", "订餐还有" + minutes.intValue() + "分钟", content , "老夏", image, form);
		List<DingDingUser> duserList = ht.find("from DingDingUser d where d.bindStatus = '1' and d.user.id is not null");
		
		int size = duserList.size();
		for (int i = 0; i <=  size / 20; i++) {
			StringBuffer sb = new StringBuffer();
			int x = (i+1) * 20 > size ? size :(i+1) * 20;
			List<DingDingUser> newList = duserList.subList(i*20, x);
			int sizeNew = newList.size();
			for (int j = 0; j < sizeNew; j++) {
				sb.append(newList.get(j).getUserid());
				if(j != sizeNew - 1) {
					sb.append(",");
				}
			}
			try {
				dingDingService.sendDDMessage(sb.toString(), message);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return getUpdateView();
	}

	public List<DayFood> getDayFoodList() {

		List<DayFood> dayFoodList = new ArrayList<DayFood>();
		for (int i = 0; i < dayFoods.length; i++) {
			if (dayFoods[i] == null) {
				continue;
			}
			dayFoodList.add(dayFoods[i]);
		}

		return dayFoodList;
	}

//	public void test() {
//		List<DayFood> list = new ArrayList<DayFood>();
//		for (int i = 0; i < dayFoods.length; i++) {
//
//			if (dayFoods[i] == null || dayFoods[i].equals("")) {
//				continue;
//			}
//			System.out.println(dayFoods[i].getDate());
//			list.add(dayFoods[i]);
//		}
//		System.out.println(list.size());
		// List<String> list = new ArrayList<String>();
		// for (int i = 0; i < res.length; i++) {
		// System.out.println(res[i]);
		// if(res[i] == null || res[i].equals("")){
		// continue;
		// }
		// list.add(res[i]);
		// }
		// System.out.println(list.size());
//	}

	public void countAdd(int calc) {
		Integer count = getInstance().getCookbookDayCount() == null
				|| getInstance().getCookbookDayCount() == 0 ? 1 : getInstance().getCookbookDayCount();
		if (calc == 0) {
			count++;
		} else {
			count--;
			dayFoods[calc] = null;
		}
		getInstance().setCookbookDayCount(count);
//		System.out.println("选了" + count + "天了");
	}

	// public Integer getCount() {
	// System.out.println(getInstance().getId());
	// if(getInstance().getId() != null && !getInstance().getId().equals("")) {
	// count = getInstance().getDayFoods().size();
	// }
	// System.out.println(count);
	// return count;
	// }

	// public void setCount(Integer count) {
	// this.count = count;
	// }

	public DayFood[] getDayFoods() {
		if (getInstance().getId() != null && !getInstance().getId().equals("")
				&& getInstance().getDayFoods() != null) {
			List<DayFood> dfList = new ArrayList<DayFood>(getInstance()
					.getDayFoods());
			for (int i = 0; i < dfList.size(); i++) {
				dayFoods[i] = dfList.get(i);
			}
			getInstance().setDayFoods(null);
		}
		for (int i = 0; i < dayFoods.length; i++) {
			if (dayFoods[i] == null) {
				dayFoods[i] = new DayFood();
			}
			if (dayFoods[i].getDate() != null) {
				dayFoods[i].setWeekday(DateUtil.getWeek(dayFoods[i].getDate())
						.getChineseName());
			}
		}
		return dayFoods;
	}

	public void setDayFoods(DayFood[] dayFoods) {
		this.dayFoods = dayFoods;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String delete(String id) {

		Cookbook cb = ht.get(Cookbook.class, id);
		if (cb != null) {
			return super.delete(id);
		}
		return null;
	}

}
